package com.kun.controller.foreign;


import com.kun.entity.Blog;
import com.kun.entity.Comment;
import com.kun.result.Result;
import com.kun.service.impl.BlogServiceImpl;
import com.kun.service.impl.CommentServiceImpl;
import com.kun.util.SysConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author SunKun
 * @since 2021-06-14
 */
@RestController
@Slf4j //日志
@CrossOrigin  //允许跨域
@ResponseBody
@RequestMapping("/kun/foreign/blog")
public class BlogController {
    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private CommentServiceImpl commentService;


    /**
     * 查询博客发布时间和数量
     * @return
     */
    @GetMapping("/queryReleaseDateAndCount")
    public Result queryReleaseDateAndCount(){
        try {
            List<Blog> blogs = blogService.queryReleaseDateAndCount();
            return Result.ok().data("blogs",blogs);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * 查询博客详情
     * @param param
     * @return
     */
    @PostMapping("/queryBlogById")
    public Result queryBlogById(@RequestBody Map<String,Object> param){
        int id = (int)param.get("id");
        Blog blog = null;
        List<Comment> comments = null;
        String[] keyWords = null;
        try {
            blog = blogService.queryBlogById(id);
            comments = commentService.queryCommentByBlogId(id, SysConstant.COMMENT_STATE_OK);
            //不为空，则进行拆分（按空格拆分）
            keyWords = blog.getKeyword().split(" ");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok().data("blog",blog).data("comments",comments).data("keyWords",keyWords);
    }

    /**
     * 查询当前博客的上一篇以及下一篇
     * @param param
     * @return
     */
    @PostMapping("/queryBlogByPrevAndNext")
    public Result queryBlogByPrevAndNext(@RequestBody Map<String,Object> param){
        int id = (int)param.get("id");
        List<Blog> blogs = null;
        try {
            blogs = blogService.queryBlogByPrevAndNext(id);
            return Result.ok().data("blogs",blogs);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

}

